// recorder.js
import { createWorkerURL } from './utils'; // 假设这个函数用来生成worker的URL

const WORKER_PATH = createWorkerURL('./recorderWorker.js'); // 使用函数生成worker路径

class Recorder {
    constructor(source, cfg = {}) {
        this.config = { ...cfg };
        this.context = source.context;
        this.node = (this.context.createScriptProcessor ||
            this.context.createJavaScriptNode).call(this.context,
            this.config.bufferLen || 4096, 2, 2); // 修正了这里，添加了缺失的括号
        this.initWorker();
        this.recording = false;
        this.currCallback = null;
        this.setupNode();
        source.connect(this.node);
        this.node.connect(this.context.destination);
    }

    // 初始化worker并设置消息监听
    initWorker() {
        this.worker = new Worker(WORKER_PATH);
        this.worker.onmessage = ({ data: blob }) => this.currCallback?.(blob);
        this.worker.postMessage({ command: 'init', config: { sampleRate: this.context.sampleRate } });
    }

    // 设置node的audioprocess事件处理
    setupNode() {
        this.node.onaudioprocess = (e) => {
            if (!this.recording) return;
            this.worker.postMessage({ command: 'record', buffer: [e.inputBuffer.getChannelData(0), e.inputBuffer.getChannelData(1)] });
        };
    }

    // 其他方法保持不变，但使用箭头函数以绑定上下文
    configure = (cfg) => {
        Object.assign(this.config, cfg);
    };

    record = () => { this.recording = true; };

    stop = () => { this.recording = false; };

    clear = () => { this.worker.postMessage({ command: 'clear' }); };

    getBuffer = (cb) => { this.currCallback = cb; this.worker.postMessage({ command: 'getBuffer' }); };

    exportWAV = (cb, type = 'audio/wav') => {
        if (!this.currCallback) throw new Error('Callback not set');
        this.currCallback = cb;
        this.worker.postMessage({ command: 'exportWAV', type });
    };
}

// 导出Recorder类和静态方法
Recorder.forceDownload = function(blob, filename = 'output.wav') {
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    link.click();
    URL.revokeObjectURL(url); // 清理URL对象
};

export default Recorder;
